import { Article } from "@/types";
import { PlusOutlined } from "@ant-design/icons";
import { Button, Form, Input, message, Modal, Tag, Upload } from "antd";
import { produce } from "immer";
import { MdEditor } from "md-editor-rt";
import "md-editor-rt/lib/style.css";
import { useEffect, useState } from "react";
import { history, useMatch } from "umi";

let timer: ReturnType<typeof setInterval>;

const normFile = (e: any) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

export default function MarkdownEditor() {
  const [article, setArticle] = useState<Article>();
  const [countdown, setCountdown] = useState(30);
  const match = useMatch("/edit/:id");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [componentDisabled, setComponentDisabled] = useState<boolean>(true);
  const [messageApi, contextHolder] = message.useMessage();
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    messageApi.open({
      type: "success",
      content: "发布成功，即将跳转到文章详情页",
      duration: 1,
      onClose: () => {
        history.replace("/detail/" + article?.id);
      }
    });
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const articleId = match?.params.id;

  const handleSubmit = () => {
    // console.log({ title, tags, content });
    // 可上传到后端或保存草稿
  };

  // 保存草稿
  const saveDraft = () => {};
  useEffect(() => {
    if (!articleId) return;
    const fetchDetail = async () => {
      try {
        // 这里指向本地 mock 文件，实际项目可替换为真实 API
        const resp = await fetch(`/api/detail`);
        const json = await resp.json();
        setArticle(json);
      } catch (err) {
        console.error("获取文章详情失败", err);
      } finally {
      }
    };
    fetchDetail();
    timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 0) {
          return 30;
        }
        return prev - 1;
      });
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className="sticky top-0 w-full h-screen flex flex-col bg-gray-100">
      {/* 标题 */}
      <div className="w-full h-12 flex items-center justify-between bg-white mb-4 p-8 rounded shadow gap-4">
        <span
          className="hover:text-blue-600 cursor-pointer flex-shrink-0"
          onClick={() => window.history.back()}
        >
          返回文章
        </span>
        <Input
          type="text"
          placeholder="请输入标题"
          className="p-2 flex-grow mx-4"
          value={article?.title}
          onChange={(e) =>
            setArticle(
              produce(article, (draft: Article) => {
                draft.title = e.target.value;
              })
            )
          }
        />

        <Button color="primary" variant="outlined" onClick={saveDraft}>
          保存草稿{`(${countdown.toString().padStart(2, "0")})`}
        </Button>
        <Button color="primary" variant="solid" onClick={showModal}>
          发布文章
        </Button>
      </div>

      <div className="w-full flex-1 overflow-auto mx-auto p-6 space-y-6 bg-white rounded shadow">
        {/* 编辑器 */}
        <MdEditor
          style={{ height: "100%" }}
          value={article?.content}
          onChange={(value) =>
            setArticle(
              produce(article, (draft: Article) => {
                // if(!draft) return;
                draft.content = value;
              })
            )
          }
          previewTheme="github"
          theme="light" // 留出暗黑切换空间
          language="zh-CN"
          codeTheme="github"
        />
      </div>
      {contextHolder}
      <Modal
        title="发布文章"
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="发布"
        cancelText="取消"
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
        >
          {/**
           * 提交时打表单信息包括：
           * 文章标签
           * 封面
           * 摘要
           */}
          <Form.Item label="文章标签">
            {article?.tags?.map((tag) => <Tag key={tag}>{tag}</Tag>)}
          </Form.Item>
          <Form.Item
            label="文章封面"
            valuePropName="fileList"
            getValueFromEvent={normFile}
          >
            <Upload action="/upload.do" listType="picture-card">
              <button
                style={{
                  color: "inherit",
                  cursor: "inherit",
                  border: 0,
                  background: "none",
                }}
                type="button"
              >
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
